package redisconfig

import (
	"github.com/go-redis/redis"
	logging "github.com/sirupsen/logrus"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"strconv"
)

//RedisClient Redis缓存客户端单例
var RedisClient *redis.Client

type RedisConf struct {
	RedisAddr   string `yaml:"RedisAddr"`
	RedisPw     string `yaml:"RedisPw"`
	RedisDbName string `yaml:"RedisDbName"`
}

//初始化redis链接
func Redis() {
	workDir, err := os.Getwd()
	if err != nil {
		logging.Error("os.Getwd error is ", err)
	}
	configFile, err := ioutil.ReadFile(workDir + "/src/gin/conf/config.yaml")
	redisConf := &RedisConf{}
	err = yaml.Unmarshal(configFile, &redisConf)

	if err != nil {
		logging.Error("配置文件读取错误:", err)
	}

	db, _ := strconv.ParseUint(redisConf.RedisDbName, 10, 64)
	client := redis.NewClient(&redis.Options{
		Addr:     redisConf.RedisAddr,
		Password: redisConf.RedisPw,
		DB:       int(db),
	})
	_, err = client.Ping().Result()
	if err != nil {
		logging.Info(err)
		panic(err)
	}
	RedisClient = client
	logging.Info("redis init success")
}
